<template>
  <div>
    <div class="mt-4">
      <el-form inline>
        <el-row>
          <el-col :span="8">
            <el-form-item>
              <el-input
                  placeholder="请输入周几或食物名称"
                  v-model="searchKeyword"
                  clearable
                  @clear="getMealDetails"
              >
                <template #append>
                  <el-button :icon="Search" @click="getMealDetails" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-button
              @click="showAddDialog"
              type="primary"
              class="add-button"
          >
            新增
          </el-button>
        </el-row>
      </el-form>

      <div>
        <el-table
            :data="mealDetailsList"
            border
            stripe
            @row-click="handleRowClick"
        >
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="id" label="ID" />
          <el-table-column prop="weekDay" label="星期几" />
          <el-table-column prop="foodId" label="食物ID" />
          <el-table-column prop="foodName" label="食物名称" />
          <el-table-column prop="foodPrice" label="食物价格" />
          <el-table-column prop="mealType" label="餐食类型" />
          <el-table-column prop="taste" label="口味" />
          <el-table-column label="操作" width="150px">
            <template #default="scope">
              <el-button
                  type="primary"
                  size="small"
                  @click="showEditDialog(scope.row.id)"
              >
                修改
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  @click="removeOne(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 对话框 -->
      <el-dialog
          v-model="mealDialog"
          :title="dialogTitle"
          width="40%"
          class="custom-dialog"
      >
        <el-form
            :model="curMeal"
            label-width="120px"
            class="custom-form"
            @submit.native.prevent
        >
          <el-form-item label="星期几">
            <el-select v-model="curMeal.weekDay" placeholder="请选择星期几">
              <el-option label="周一" value="周一"></el-option>
              <el-option label="周二" value="周二"></el-option>
              <el-option label="周三" value="周三"></el-option>
              <el-option label="周四" value="周四"></el-option>
              <el-option label="周五" value="周五"></el-option>
              <el-option label="周六" value="周六"></el-option>
              <el-option label="周日" value="周日"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="食物名称">
            <el-input
                v-model="curMeal.foodName"
                class="form-input"
            />
          </el-form-item>
          <el-form-item label="食物价格">
            <el-input v-model="curMeal.foodPrice" class="form-input" />
          </el-form-item>
          <el-form-item label="餐食类型">
            <el-select v-model="curMeal.mealType" placeholder="请选择餐食类型">
              <el-option label="主食" value="1"></el-option>
              <el-option label="菜" value="2"></el-option>
              <el-option label="汤" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="口味">
            <el-input v-model="curMeal.taste" class="form-input" />
          </el-form-item>

        </el-form>
        <template #footer>
          <el-button
              @click="optOne"
              type="primary"
              class="dialog-footer-button"
          >
            提交
          </el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { Plus, Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/axios/http';

const searchKeyword = ref('');
const mealDetailsList = ref([]);
const mealDialog = ref(false);
let dialogTitle = reactive('');
const curMeal = reactive({
  weekDay: '',
  foodName: '',
  foodPrice: null,
  mealType: null,
  taste: '',
  isDeleted: 0
});

function closeMealDialog() {
  mealDialog.value = false;
  Object.keys(curMeal).forEach(key => delete curMeal[key]);
  curMeal.isDeleted = 0;
}

const getMealDetails = async () => {
  try {
    const params = {
      keyword: searchKeyword.value || '%'
    };
    const res = await http.post('/lyy/get_meals', params);
    if (res.data.result ==='success') {
      mealDetailsList.value = res.data.data.map(item => ({
        id: item.id,
        weekDay: item.week_day,
        foodId: item.food_id,
        foodName: item.food_name,
        foodPrice: item.food_price,
        mealType: item.meal_type,
        taste: item.taste,
        isDeleted: item.is_deleted
      }));
      if (mealDetailsList.value.length === 0) {
        ElMessage.info('没有找到匹配的膳食数据');
      }
    } else {
      ElMessage.error('获取膳食数据失败：' + res.data.error);
    }
  } catch (error) {
    console.error('请求后端接口失败：', error);
    ElMessage.error('请求后端接口失败，请稍后重试');
  }
};

function addOne() {
  return new Promise((resolve, reject) => {
    const requestData = {
      weekDay: curMeal.weekDay,
      foodName: curMeal.foodName,
      foodPrice: curMeal.foodPrice,
      mealType: parseInt(curMeal.mealType), // 将mealType转换为数字
      taste: curMeal.taste,
      isDeleted: curMeal.isDeleted
    };
    http.post('/lyy/add_meal', requestData)
        .then(mealRes => {
          if (mealRes.data.result ==='success') {
            ElMessage.success('新增成功');
            resolve();
          } else {
            ElMessage.error('新增餐食信息失败: ' + mealRes.data.error);
            reject();
          }
        })
        .catch(mealError => {
          console.error('新增餐食信息失败:', mealError);
          ElMessage.error('新增餐食信息失败，请稍后重试');
          reject();
        });
  });
}

function editOne() {
  return new Promise((resolve, reject) => {
    const editParam = {
      ...curMeal
    };
    http.post('/lyy/edit_mealby', editParam)
        .then((res) => {
          if (res.data.result ==='success') {
            ElMessage.success('修改成功');
            resolve();
          } else {
            ElMessage.error('修改失败: ' + res.data.error);
            reject();
          }
        })
        .catch((error) => {
          console.error('修改失败:', error);
          ElMessage.error('修改失败，请稍后重试');
          reject();
        });
  });
}

// 删除一条数据
const removeOne = (id) => {
  ElMessageBox.confirm('确定要删除该记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(async () => {
        try {
          const res = await http.post('/lyy/delete_mealby', { id });
          if (res.data.result ==='success') {
            ElMessage.success('删除成功');
            await getMealDetails();
          } else {
            ElMessage.error('删除失败: ' + res.data.error);
          }
        } catch (error) {
          console.error('删除失败:', error);
          ElMessage.error('删除失败，请稍后重试');
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      });
};

function showEditDialog(id) {
  const targetMeal = mealDetailsList.value.find(item => item.id === id);
  if (targetMeal) {
    Object.assign(curMeal, targetMeal);
    mealDialog.value = true;
    dialogTitle = '修改膳食信息';
  }
}

function showAddDialog() {
  closeMealDialog();
  mealDialog.value = true;
  dialogTitle = '新增膳食信息';
}

async function optOne() {
  if (dialogTitle === '新增膳食信息') {
    await addOne();
    await getMealDetails();
    closeMealDialog();
  } else if (dialogTitle === '修改膳食信息') {
    await editOne();
    await getMealDetails();
    closeMealDialog();
  }
}

function handleRowClick(row) {
  // 点击表格行时，可以选择是否进行一些操作，比如展开详细信息等，这里暂未实现具体逻辑
}

onMounted(() => {
  getMealDetails();
});
</script>

<style scoped>
.mt-4 {
  margin-top: 16px;
}

.add-button {
  margin-left: 10px;
}

.custom-dialog {
  padding: 20px; /* 确保有足够的内边距 */
  box-sizing: border-box; /* 确保内边距不会影响对话框的尺寸 */
}

.custom-form {
  width: 100%;
}

.form-input {
  width: 100%;
}

.dialog-footer-button {
  float: right;
  margin: 0; /* 移除可能的外边距 */
  padding: 10px 10px; /* 调整按钮的内边距 */
}
</style>